package com.atguigu.flinkWindow;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * 全窗口函数  开的窗只是计算单元(就是分割计算 ) 计算的还是所有数据
 * @author wky
 * @create 2021-07-16-19:04
 */
public class ProcessWindowFunction {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();
        senv.setParallelism(1);
        DataStreamSource<String> streamSource = senv.socketTextStream("hadoop102", 9999);
        SingleOutputStreamOperator<Tuple2<String, Long>> streamOperator = streamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] split = s.split(" ");
                for (String s1 : split) {
                    collector.collect(Tuple2.of(s1, 1L));
                }
            }
        });
        KeyedStream<Tuple2<String, Long>, Tuple> keyedStream = streamOperator.keyBy(0);
        WindowedStream<Tuple2<String, Long>, Tuple, TimeWindow> window = keyedStream.window(TumblingProcessingTimeWindows.of(Time.seconds(5)));
        //TODO  可以求百分之多少的数据或者求平均数这种需要把全部数据拿到之后再求的场景。 in out key w
        //每五秒钟统计一次 求a出现的次数占总次数的多少
        window.process(new org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction<Tuple2<String, Long>, String, Tuple, TimeWindow>() {
            double s = 0;
            double a =0;
            @Override
            public void process(Tuple tuple, Context context, Iterable<Tuple2<String, Long>> elements, Collector<String> out) throws Exception {

                for (Tuple2<String, Long> element : elements) {
                    ++s;
                    if ("a".equals(element.f0)){
                        ++a;
                    }
                }

                double l = a / s;
                out.collect(l+"");

            }
        }).print();
        senv.execute();
    }
}
